﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using Monkey.Warrenty.Data.Interfaces;
using Monkey.Warrenty.EntityModel;

namespace Monkey.Warrenty.Data
{
    public class DealerGroupDao : IDealerGroupDao
    {
        public List<DealerGroup> GetAllDealerGroups()
        {
            List<DealerGroup> dealerGroups;

            using (var context = new MonkeyWarrantyEntities())
            {
                dealerGroups = context.DealerGroups.OrderBy(x => x.Name).ToList();
            }

            return dealerGroups;
        }

        public DealerGroup AddDealerGroup(DealerGroup dealerGroup)
        {
            using (var context = new MonkeyWarrantyEntities())
            {
                context.DealerGroups.AddObject(dealerGroup);
                context.SaveChanges();
            }

            return dealerGroup;
        }

        public void UpdateDealerGroup(DealerGroup dealerGroup)
        {
            // throw new System.NotImplementedException();
            if (dealerGroup == null || dealerGroup.Id == 0) return;

            using (var context = new MonkeyWarrantyEntities())
            {
                context.DealerGroups.Attach(dealerGroup);
                context.ObjectStateManager.ChangeObjectState(dealerGroup, EntityState.Modified);
                context.SaveChanges();
            }
        }

        public void DeleteDealerGroup(int dealerGroupId)
        {
            if (dealerGroupId <= 0) return;
            using (var context = new MonkeyWarrantyEntities())
            {
                var dealerGroup = context.DealerGroups.First(g => g.Id == dealerGroupId);

                context.DeleteObject(dealerGroup);

                context.SaveChanges();
            }
        }

        public int GetMaxId()
        {
            var maxId = 0;

            using (var context = new MonkeyWarrantyEntities())
            {
                var dealerGroup = context.DealerGroups.OrderByDescending(x => x.Id).FirstOrDefault();
                if (dealerGroup != null) maxId = dealerGroup.Id;
            }

            return maxId;
        }

        public int GetCurrentIdentity()
        {
            long? identity;
            using (var context = new MonkeyWarrantyEntities())
            {
                identity = context.GetIdentity("DealerGroups").SingleOrDefault();
            }

            return identity.HasValue ? (int)identity.Value : 0;
        }

        public DealerGroup GetById(int id)
        {
            using (var context = new MonkeyWarrantyEntities())
            {
                return context.DealerGroups.FirstOrDefault(x => x.Id == id);
            }
        }
    }
}
